<template>
  <div>
    <a-card :bodyStyle="tstyle" :bordered="false">
      <div v-if="hasPerm('property:page')" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="任务名称：">
                <a-input v-model="queryParam.connectName" allow-clear placeholder="请输入任务名称" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :alert="true"
        :columns="columns"
        :data="loadData"
        :rowKey="(record) => record.id"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <template v-if="hasPerm('property:add')" slot="operator" class="table-operator">
          <a-button v-if="hasPerm('property:add')" icon="plus" type="primary" @click="$refs.addForm.add()">
            新增
          </a-button>
        </template>
        <span slot="triggerState" slot-scope="text, record">
          <a-switch @change="jobStateChange(record)" :checked="record.triggerStatus===1"></a-switch>
          <span @click="jobStateChange(record)">{{ record.triggerStatus === 1 ? '停止' : '启动' }}</span>
        </span>
        <a-popover
          slot-scope="text, record"
          slot="action"
          v-model="record.visiblePopover"
          trigger="hover"
          placement="bottom"
          title="">
          <div
            slot="content">
            <a-popconfirm
              @cancel="record.visiblePopover=false"
              v-if="hasPerm('property:edit')"
              placement="left"
              title="确定立即执行?"
              @confirm="() => triggerChange(record)">
              <div style="height: 30px">
                <a>执行一次</a>
              </div>
            </a-popconfirm>
            <div style="height: 30px">
              <a v-if="hasPerm('property:edit')" @click="edit(record)">编辑</a>
            </div>
            <div style="height: 30px">
              <a v-if="hasPerm('property:edit')" @click="viewDetail(record)">查看</a>
            </div>
            <a-popconfirm
              @cancel="record.visiblePopover=false"
              v-if="hasPerm('property:delete')"
              placement="topRight"
              title="确认删除？"
              @confirm="() => deleteItem(record)">
              <div style="height: 30px">
                <a>删除</a>
              </div>
            </a-popconfirm>
          </div>
          <icon-font
            :style="{ 'font-size':'24px','color':'blue4'}"
            type="icon-more">
          </icon-font>
        </a-popover>
      </s-table>
    </a-card>
    <add-form @ok="handleOk" ref="addForm"></add-form>
    <task-detail-form ref="viewDetailForm"></task-detail-form>
  </div>
</template>
<script>

import { STable } from '@/components'
import addForm from './addForm'
import taskDetailForm from './taskDetailForm'
import {
  deleteCatchTask,
  jobTaskChange,
  jobTrigger,
  queryCatchTaskList
} from '@/api/modular/main/knowl/catchtask_config/catchTaskConfigManager'

export default {
  components: {
    STable,
    addForm,
    taskDetailForm
  },
  props: {
    queryParam: {
      type: Object,
      default: function() {
        return {}
      }
    },
    modal: {
      type: Boolean,
      default: function() {
        return false
      }
    }
  },
  data() {
    return {
      // 表头
      columns: [
        {
          title: '采集任务名称',
          align: 'center',
          dataIndex: 'taskName',
          ellipsis: true
        },
        {
          title: '数据源类型',
          align: 'center',
          dataIndex: 'dataSource.datasourceType'
        },
        {
          title: '数据源',
          align: 'center',
          dataIndex: 'dataSource.databaseName'
        },
        {
          title: '总量',
          align: 'center',
          dataIndex: 'total',
          width: '100px'
        },
        {
          title: '已采数量',
          align: 'center',
          dataIndex: 'datasourceType',
          width: '100px'
        },
        {
          title: '采集Cron',
          align: 'center',
          dataIndex: 'jobCron'
        },
        {
          title: '创建者',
          align: 'center',
          dataIndex: 'createUser',
          ellipsis: true
        },
        {
          title: '创建时间',
          align: 'center',
          ellipsis: true,
          customRender: (t, r, index) => {
            return r.createTime.substring(0, 19)
          }
        },
        {
          title: '状态',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'triggerState' }
        }
      ],
      tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return queryCatchTaskList(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  created() {
    if (this.hasPerm('property:edit') || this.hasPerm('property:delete')) {
      this.columns.push({
        title: '操作',
        align: 'center',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  methods: {
    edit(record) {
      record.visiblePopover = false
      this.$refs.addForm.edit(record)
    },
    viewDetail(record) {
      record.visiblePopover = false
      this.$refs.viewDetailForm.loadData(record)
    },
    tableReload() {
      this.handleOk()
    },
    jobStateChange(record) {
      this.$refs.table.localLoading = true
      jobTaskChange({ 'jobId': record.jobId }, record.triggerStatus === 1).then((res) => {
        if (res.code === 200) {
          const origin = this.$refs.table.localDataSource
          const index = origin.findIndex((it) => it.id === record.id)
          const old = origin[index]
          old.triggerStatus = old.triggerStatus === 1 ? 0 : 1
          this.$refs.table.replaceItem(index, old)
          this.$message.success('操作成功!')
        }
      })
        .catch((e) => {
          console.log(e)
        }).finally(() => {
        this.$refs.table.localLoading = false
      })
    },
    triggerChange(record) {
      record.visiblePopover = false
      this.$refs.table.localLoading = true
      jobTrigger({ 'id': record.jobId }).then((res) => {
        if (res.code === 200) {
          this.$message.success('操作成功!')
        }
      })
        .catch((e) => {
          console.log(e)
        }).finally(() => {
        this.$refs.table.localLoading = false
      })
    },
    deleteItem(record) {
      record.visiblePopover = false
      deleteCatchTask(record)
        .then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            const msg = res['message']
            if (msg) {
              this.$message.error(msg)
            } else {
              this.$message.error('删除失败')
            }
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },

    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
